package com.nextdiscover.esp32test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {
    private Button btnSend;
    private Button btnStop;
    private int sendNum=0;
    int recvNum=0;

    private EditText etTargetIP;
    private EditText etTargetPort;
    private EditText etLocalIP;
    private EditText etLocalPort;

    private EditText etSSID;
    private EditText etPassword;

    private Spinner spEncrypt;

    private String strTargetIP;
    private String strTargetPort;
    private String strLocalIP;
    private String strLocalPort;

    private String strSSID;
    private String strPassword;
    private String strEncrypt;

    private Button btnConnect;

    DatagramSocket socket;
    InetAddress addr;

    public int STOPNUM = 1024;
    public String SOTFAPSSID = "Smart-AW-HOSTAPD";

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context=this.getBaseContext();
        init();

    }

    private void init(){
        btnSend = (Button) this.findViewById(R.id.btnSend);
        btnSend.setOnClickListener(click);
        btnStop = (Button) this.findViewById(R.id.btnStop);
        btnStop.setOnClickListener(click);

        etTargetIP= (EditText) findViewById(R.id.etTargetIP);
        etTargetPort= (EditText) findViewById(R.id.etTargetPort);
        etLocalIP= (EditText) findViewById(R.id.etLocalIP);
        etLocalPort= (EditText) findViewById(R.id.etLocalPort);

        etSSID= (EditText) findViewById(R.id.etSSID);
        etPassword= (EditText) findViewById(R.id.etPassword);

        spEncrypt= (Spinner) findViewById(R.id.spEncrypt);
        spEncrypt.setOnItemSelectedListener(select);
        spEncrypt.setSelection(1,true);
        strEncrypt= String.valueOf(spEncrypt.getSelectedItemId());

        btnConnect= (Button) findViewById(R.id.btnConnect);
        btnConnect.setOnClickListener(click);

    }

    private Spinner.OnItemSelectedListener select= new Spinner.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String[] languages = getResources().getStringArray(R.array.encrypt);
            Log.e("Encrypt:",languages[position]);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    private Button.OnClickListener click =new Button.OnClickListener(){
        public void onClick(View v){
            switch (v.getId()){
                case R.id.btnStop:{
                    sendNum = STOPNUM;
                    recvNum = STOPNUM;
                    break;
                }
                case R.id.btnConnect:{

                    SmartlinkInfo info = new SmartlinkInfo();
                    info.ssid=SOTFAPSSID;
                    info.password="wifi1111";
                    info.wlansecurity=3;


                    //获取屏幕上输入的IP\port\ssid等信息
                    strTargetIP= String.valueOf(etTargetIP.getText());
                    strTargetPort= String.valueOf(etTargetPort.getText());
                    strLocalIP= String.valueOf(etLocalIP.getText());
                    strLocalPort= String.valueOf(etLocalPort.getText());
                    strSSID= String.valueOf(etSSID.getText());
                    strPassword = String.valueOf(etPassword.getText());
                    Log.e("Info",strTargetIP+" "+strTargetPort);
                    strSSID= String.valueOf(etSSID.getText());
                    strPassword = String.valueOf(etPassword.getText());

                    try {
                        socket = new DatagramSocket(Integer.parseInt(strTargetPort));
                        socket.setBroadcast(true);
                        addr = InetAddress.getByName(strTargetIP);
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }

                    connectWifi(info);


                    break;
                }
                default:break;
            }
        }
    };

    private int connectWifi(SmartlinkInfo info) {

        WifiAdmin mWifiAdmin = new WifiAdmin(this);
        mWifiAdmin.openWifi();
        boolean FOUNDSOFTAP=false;
        for(int j=0;j<20;j++) {
            mWifiAdmin.startScan();
            for (int i = 0; i < mWifiAdmin.getWifiList().size(); i++) {
                //Log.e("WIFIINFO", i+": " + mWifiAdmin.getWifiList().get(i).SSID);
                if (mWifiAdmin.getWifiList().get(i).SSID.equals(SOTFAPSSID)) {
                    FOUNDSOFTAP=true;
                    Log.e("WIFIINFO", i+": " + mWifiAdmin.getWifiList().get(i).SSID);
                    Log.e("WIFIINFO", "FOUND SOFTAP.");
                    break;
                }
            }
            if(FOUNDSOFTAP){
                mWifiAdmin.creatWifiLock();
                WifiConfiguration config = mWifiAdmin.CreateWifiInfo(info.ssid,info.password,info.wlansecurity);
                mWifiAdmin.addNetwork(config);
                mWifiAdmin.releaseWifiLock();
                break;
            }
        }

        if (context != null) {
            Log.e("SLEEP","if (context != null)");
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            Log.e("SLEEP"," ConnectivityManager mConnectivityManager = (ConnectivityManager) context");
            //NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            //Log.e("SLEEP"," NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();");

            while (mConnectivityManager.getActiveNetworkInfo()==null) {//WIFI_STATE_ENABLING = 2;
                Log.e("SLEEP", "mNetworkInfo==null sleep 2 s~");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            while (!mConnectivityManager.getActiveNetworkInfo().isConnected()) {//WIFI_STATE_ENABLING = 2;
                Log.e("SLEEP", "!mNetworkInfo.isConnected() sleep 2 s~");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            Log.e("mNetworkInfo","mNetworkInfo == null");
        }

        //打开接收线程
        Thread recvThread = new Thread(recvRunnable);
        recvThread.start();

        //打开发送线程
        Thread sendThread = new Thread(sendRunnable);
        sendThread.start();
        /*
        mWifiAdmin.creatWifiLock();
        WifiConfiguration config = mWifiAdmin.CreateWifiInfo(info.ssid,info.password,info.wlansecurity);
        mWifiAdmin.addNetwork(config);
        mWifiAdmin.releaseWifiLock();
        */
        return 0;
    }

    private Runnable sendRunnable = new Runnable() {
        @Override
        public void run() {
            String strInfo="::SSID::"+strSSID+"::Password::"+ strPassword+"::End::";

            try {

                byte[] buffer = strInfo.getBytes();
                DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                packet.setAddress(addr);
                packet.setPort(Integer.parseInt(strTargetPort));

                for(sendNum=0;sendNum<60;sendNum++) {
                    socket.send(packet);
                    Thread.sleep(1000);
                    Log.e("Send","Num:"+sendNum+"  "+strInfo);
                }

            } catch (Exception e) {
                e.printStackTrace();
                Log.e("发送线程",e+"");
            }

                /*
                SmartlinkInfo info = new SmartlinkInfo();
                info.ssid=strSSID;
                info.password=strPassword;
                info.wlansecurity=3;
                connectWifi(info);
                */
        }
    };

    private Runnable recvRunnable = new Runnable() {
        @Override
        public void run() {

            try {
                byte[] buffer ="XX".getBytes();
                DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                packet.setAddress(addr);
                packet.setPort(Integer.parseInt(strTargetPort));
                for(recvNum=0;recvNum<65;recvNum++) {
                    Log.e("recv", "正在接收..."+recvNum );
                    socket.receive(packet);
                    if(new String(packet.getData()).equals("OK")){
                        sendNum = STOPNUM;
                        Log.e("recv", "收到消息:" + new String(packet.getData()));
                        break;
                    }
                    Thread.sleep(1000);
                }

                /*
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //mTextView.setText("收到消息" + new String(packet.getData()) + ":" + String.valueOf(++index));
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                */
                //socket.close();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("接收线程",e+"");
            }

        }

    };
}
